import org.junit.Test;

import javax.management.Query;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Semaphore;

/**
 * @author jcl_hqu
 * @date 2021/4/6 19:20
 */


public class MySemaphore {
    private int value; // 资源数
    private MyProcess L=new MyProcess();

    public MySemaphore(int v) {
        value=v;
    }

    public  void P() throws InterruptedException {
        value--;
        if(value<0){
//            Thread.currentThread().getPriority()
            block(L,Thread.currentThread().getId());
        }
    }

        public  void  V() {  //相当于释放资源
        value++;
        if(value<=0){
            //remove a process P from S.L;
            wakeup(L);
        }
    }

    public MyProcess getL() {
        return L;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public static Thread findThread(long threadId) {
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        while(group != null) {
            Thread[] threads = new Thread[(int)(group.activeCount() * 1.2)];
            int count = group.enumerate(threads, true);
            for(int i = 0; i < count; i++) {
                if(threadId == threads[i].getId()) {
                    return threads[i];
                }
            }
            group = group.getParent();
        }
        return null;
    }

    private void wakeup(MyProcess p) {
        Long thread_id=p.pop();
        System.out.println("唤醒"+thread_id);
        Thread s = findThread(thread_id);
    }

    private void block(MyProcess p,Long thread_id) throws InterruptedException {
        p.add(thread_id);
        System.out.println("阻塞"+thread_id);
        Thread s = findThread(thread_id);
//        System.out.println("阻塞"+s.getName());
        s.interrupt();
    }

    public  class MyProcess {
        private Queue<Long> list_id=new LinkedList<>();  //线程id

        public void add(long id){
            list_id.offer(id);
        }

        public Queue<Long> getList_id() {
            return list_id;
        }

        public Long pop(){
            Long thread_id=list_id.poll();
            return thread_id;
        }

    }

}
